﻿using LiteFramework.Enum;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

namespace LiteFramework
{
    /// <summary>
    /// 
    /// </summary>
    public class TextHelper
    {
        private const string simplified = "皑蔼碍爱翱袄奥坝罢摆败颁办绊帮绑镑谤剥饱宝报鲍辈贝钡狈备惫绷笔毕毙闭边编贬变辩辫鳖瘪濒滨宾摈饼拨钵铂驳卜补参蚕残惭惨灿苍舱仓沧厕侧册测层诧搀掺蝉馋谗缠铲产阐颤场尝长偿肠厂畅钞车彻尘陈衬撑称惩诚骋痴迟驰耻齿炽冲虫宠畴踌筹绸丑橱厨锄雏础储触处传疮闯创锤纯绰辞词赐聪葱囱从丛凑窜错达带贷担单郸掸胆惮诞弹当挡党荡档捣岛祷导盗灯邓敌涤递缔点垫电淀钓调迭谍叠钉顶锭订东动栋冻斗犊独读赌镀锻断缎兑队对吨顿钝夺鹅额讹恶饿儿尔饵贰发罚阀珐矾钒烦范贩饭访纺飞废费纷坟奋愤粪丰枫锋风疯冯缝讽凤肤辐抚辅赋复负讣妇缚该钙盖干赶秆赣冈刚钢纲岗皋镐搁鸽阁铬个给龚宫巩贡钩沟构购够蛊顾剐关观馆惯贯广规硅归龟闺轨诡柜贵刽辊滚锅国过骇韩汉阂鹤贺横轰鸿红后壶护沪户哗华画划话怀坏欢环还缓换唤痪焕涣黄谎挥辉毁贿秽会烩汇讳诲绘荤浑伙获货祸击机积饥讥鸡绩缉极辑级挤几蓟剂济计记际继纪夹荚颊贾钾价驾歼监坚笺间艰缄茧检碱硷拣捡简俭减荐槛鉴践贱见键舰剑饯渐溅涧浆蒋桨奖讲酱胶浇骄娇搅铰矫侥脚饺缴绞轿较秸阶节茎惊经颈静镜径痉竞净纠厩旧驹举据锯惧剧鹃绢杰洁结诫届紧锦仅谨进晋烬尽劲荆觉决诀绝钧军骏开凯颗壳课垦恳抠库裤夸块侩宽矿旷况亏岿窥馈溃扩阔蜡腊莱来赖蓝栏拦篮阑兰澜谰揽览懒缆烂滥捞劳涝乐镭垒类泪篱离里鲤礼丽厉励砾历沥隶俩联莲连镰怜涟帘敛脸链恋炼练粮凉两辆谅疗辽镣猎临邻鳞凛赁龄铃凌灵岭领馏刘龙聋咙笼垄拢陇楼娄搂篓芦卢颅庐炉掳卤虏鲁赂禄录陆驴吕铝侣屡缕虑滤绿峦挛孪滦乱抡轮伦仑沦纶论萝罗逻锣箩骡骆络妈玛码蚂马骂吗买麦卖迈脉瞒馒蛮满谩猫锚铆贸么霉没镁门闷们锰梦谜弥觅绵缅庙灭悯闽鸣铭谬谋亩钠纳难挠脑恼闹馁腻撵捻酿鸟聂啮镊镍柠狞宁拧泞钮纽脓浓农疟诺欧鸥殴呕沤盘庞国爱赔喷鹏骗飘频贫苹凭评泼颇扑铺朴谱脐齐骑岂启气弃讫牵扦钎铅迁签谦钱钳潜浅谴堑枪呛墙蔷强抢锹桥乔侨翘窍窃钦亲轻氢倾顷请庆琼穷趋区躯驱龋颧权劝却鹊让饶扰绕热韧认纫荣绒软锐闰润洒萨鳃赛伞丧骚扫涩杀纱筛晒闪陕赡缮伤赏烧绍赊摄慑设绅审婶肾渗声绳胜圣师狮湿诗尸时蚀实识驶势释饰视试寿兽枢输书赎属术树竖数帅双谁税顺说硕烁丝饲耸怂颂讼诵擞苏诉肃虽绥岁孙损笋缩琐锁獭挞抬摊贪瘫滩坛谭谈叹汤烫涛绦腾誊锑题体屉条贴铁厅听烃铜统头图涂团颓蜕脱鸵驮驼椭洼袜弯湾顽万网韦违围为潍维苇伟伪纬谓卫温闻纹稳问瓮挝蜗涡窝呜钨乌诬无芜吴坞雾务误锡牺袭习铣戏细虾辖峡侠狭厦锨鲜纤咸贤衔闲显险现献县馅羡宪线厢镶乡详响项萧销晓啸蝎协挟携胁谐写泻谢锌衅兴汹锈绣虚嘘须许绪续轩悬选癣绚学勋询寻驯训讯逊压鸦鸭哑亚讶阉烟盐严颜阎艳厌砚彦谚验鸯杨扬疡阳痒养样瑶摇尧遥窑谣药爷页业叶医铱颐遗仪彝蚁艺亿忆义诣议谊译异绎荫阴银饮樱婴鹰应缨莹萤营荧蝇颖哟拥佣痈踊咏涌优忧邮铀犹游诱舆鱼渔娱与屿语吁御狱誉预驭鸳渊辕园员圆缘远愿约跃钥岳粤悦阅云郧匀陨运蕴酝晕韵杂灾载攒暂赞赃脏凿枣灶责择则泽贼赠扎札轧铡闸诈斋债毡盏斩辗崭栈战绽张涨帐账胀赵蛰辙锗这贞针侦诊镇阵挣睁狰帧郑证织职执纸挚掷帜质钟终种肿众诌轴皱昼骤猪诸诛烛瞩嘱贮铸筑驻专砖转赚桩庄装妆壮状锥赘坠缀谆浊兹资渍踪综总纵邹诅组钻致钟么为只凶准启板里雳余链泄";
        private const string traditional = "皚藹礙愛翺襖奧壩罷擺敗頒辦絆幫綁鎊謗剝飽寶報鮑輩貝鋇狽備憊繃筆畢斃閉邊編貶變辯辮鼈癟瀕濱賓擯餅撥缽鉑駁蔔補參蠶殘慚慘燦蒼艙倉滄廁側冊測層詫攙摻蟬饞讒纏鏟産闡顫場嘗長償腸廠暢鈔車徹塵陳襯撐稱懲誠騁癡遲馳恥齒熾沖蟲寵疇躊籌綢醜櫥廚鋤雛礎儲觸處傳瘡闖創錘純綽辭詞賜聰蔥囪從叢湊竄錯達帶貸擔單鄲撣膽憚誕彈當擋黨蕩檔搗島禱導盜燈鄧敵滌遞締點墊電澱釣調叠諜疊釘頂錠訂東動棟凍鬥犢獨讀賭鍍鍛斷緞兌隊對噸頓鈍奪鵝額訛惡餓兒爾餌貳發罰閥琺礬釩煩範販飯訪紡飛廢費紛墳奮憤糞豐楓鋒風瘋馮縫諷鳳膚輻撫輔賦複負訃婦縛該鈣蓋幹趕稈贛岡剛鋼綱崗臯鎬擱鴿閣鉻個給龔宮鞏貢鈎溝構購夠蠱顧剮關觀館慣貫廣規矽歸龜閨軌詭櫃貴劊輥滾鍋國過駭韓漢閡鶴賀橫轟鴻紅後壺護滬戶嘩華畫劃話懷壞歡環還緩換喚瘓煥渙黃謊揮輝毀賄穢會燴彙諱誨繪葷渾夥獲貨禍擊機積饑譏雞績緝極輯級擠幾薊劑濟計記際繼紀夾莢頰賈鉀價駕殲監堅箋間艱緘繭檢堿鹼揀撿簡儉減薦檻鑒踐賤見鍵艦劍餞漸濺澗漿蔣槳獎講醬膠澆驕嬌攪鉸矯僥腳餃繳絞轎較稭階節莖驚經頸靜鏡徑痙競淨糾廄舊駒舉據鋸懼劇鵑絹傑潔結誡屆緊錦僅謹進晉燼盡勁荊覺決訣絕鈞軍駿開凱顆殼課墾懇摳庫褲誇塊儈寬礦曠況虧巋窺饋潰擴闊蠟臘萊來賴藍欄攔籃闌蘭瀾讕攬覽懶纜爛濫撈勞澇樂鐳壘類淚籬離裏鯉禮麗厲勵礫曆瀝隸倆聯蓮連鐮憐漣簾斂臉鏈戀煉練糧涼兩輛諒療遼鐐獵臨鄰鱗凜賃齡鈴淩靈嶺領餾劉龍聾嚨籠壟攏隴樓婁摟簍蘆盧顱廬爐擄鹵虜魯賂祿錄陸驢呂鋁侶屢縷慮濾綠巒攣孿灤亂掄輪倫侖淪綸論蘿羅邏鑼籮騾駱絡媽瑪碼螞馬罵嗎買麥賣邁脈瞞饅蠻滿謾貓錨鉚貿麽黴沒鎂門悶們錳夢謎彌覓綿緬廟滅憫閩鳴銘謬謀畝鈉納難撓腦惱鬧餒膩攆撚釀鳥聶齧鑷鎳檸獰甯擰濘鈕紐膿濃農瘧諾歐鷗毆嘔漚盤龐國愛賠噴鵬騙飄頻貧蘋憑評潑頗撲鋪樸譜臍齊騎豈啓氣棄訖牽扡釺鉛遷簽謙錢鉗潛淺譴塹槍嗆牆薔強搶鍬橋喬僑翹竅竊欽親輕氫傾頃請慶瓊窮趨區軀驅齲顴權勸卻鵲讓饒擾繞熱韌認紉榮絨軟銳閏潤灑薩鰓賽傘喪騷掃澀殺紗篩曬閃陝贍繕傷賞燒紹賒攝懾設紳審嬸腎滲聲繩勝聖師獅濕詩屍時蝕實識駛勢釋飾視試壽獸樞輸書贖屬術樹豎數帥雙誰稅順說碩爍絲飼聳慫頌訟誦擻蘇訴肅雖綏歲孫損筍縮瑣鎖獺撻擡攤貪癱灘壇譚談歎湯燙濤縧騰謄銻題體屜條貼鐵廳聽烴銅統頭圖塗團頹蛻脫鴕馱駝橢窪襪彎灣頑萬網韋違圍爲濰維葦偉僞緯謂衛溫聞紋穩問甕撾蝸渦窩嗚鎢烏誣無蕪吳塢霧務誤錫犧襲習銑戲細蝦轄峽俠狹廈鍁鮮纖鹹賢銜閑顯險現獻縣餡羨憲線廂鑲鄉詳響項蕭銷曉嘯蠍協挾攜脅諧寫瀉謝鋅釁興洶鏽繡虛噓須許緒續軒懸選癬絢學勳詢尋馴訓訊遜壓鴉鴨啞亞訝閹煙鹽嚴顔閻豔厭硯彥諺驗鴦楊揚瘍陽癢養樣瑤搖堯遙窯謠藥爺頁業葉醫銥頤遺儀彜蟻藝億憶義詣議誼譯異繹蔭陰銀飲櫻嬰鷹應纓瑩螢營熒蠅穎喲擁傭癰踴詠湧優憂郵鈾猶遊誘輿魚漁娛與嶼語籲禦獄譽預馭鴛淵轅園員圓緣遠願約躍鑰嶽粵悅閱雲鄖勻隕運蘊醞暈韻雜災載攢暫贊贓髒鑿棗竈責擇則澤賊贈紮劄軋鍘閘詐齋債氈盞斬輾嶄棧戰綻張漲帳賬脹趙蟄轍鍺這貞針偵診鎮陣掙睜猙幀鄭證織職執紙摯擲幟質鍾終種腫衆謅軸皺晝驟豬諸誅燭矚囑貯鑄築駐專磚轉賺樁莊裝妝壯狀錐贅墜綴諄濁茲資漬蹤綜總縱鄒詛組鑽緻鐘麼為隻兇準啟闆裡靂餘鍊洩";

        public static string Amead(string s, char sp)
        {
            if (string.IsNullOrEmpty(s) || (s.Length <= 1))
            {
                return s;
            }
            StringBuilder builder = new StringBuilder();
            bool flag = false;
            for (int i = 0; i < s.Length; i++)
            {
                char c = s[i];
                if ((i > 0) && char.IsUpper(c))
                {
                    if (!flag)
                    {
                        builder.Append(sp);
                        flag = true;
                    }
                }
                else
                {
                    flag = false;
                }

                builder.Append(c);
            }
            return builder.ToString();
        }

        public static int Count(string s1, string s2)
        {
            int num = 0;
            if (!string.IsNullOrEmpty(s1) && !string.IsNullOrEmpty(s2))
            {
                int index = -1;
                do
                {
                    index = s1.IndexOf(s2, (int)(index + 1));
                    if (index != -1)
                    {
                        num++;
                    }
                }
                while ((index != -1) && ((index + 1) < s1.Length));
            }
            return num;
        }

        /// <summary>
        /// 词首字母大写(可能多个，如: hello world -> Hello World)
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string UpperFirstChar(string s)
        {
            if (s == null)
                return s;
            else
                return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s);
        }

        /// <summary>
        /// 首字母大写(字符串中的每一个字每大写，如: hello world -> Hello world)
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string UpperFirstCharOnly(string s)
        {
            if (s == null || s.Length == 0)
                return s;
            else if (s.Length == 1)
                return s.ToUpper();
            else
                return s.Substring(0, 1).ToUpper() + s.Substring(1);
        }

        /// <summary>
        /// 字符串为null或长度为0时，将其置为一个空格
        /// </summary>
        /// <param name="s"></param>
        public static void EmptyToSpace(ref string s)
        {
            if ((s == null) || (s.Length == 0))
            {
                s = " ";
            }
        }

        /// <summary>
        /// 将字符串转换为等效的8位无符号整数数组，并反序列化为对象图形
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static object FromBase64(string data)
        {
            if (!string.IsNullOrEmpty(data))
            {
                return ByteHelper.Deserialize(Convert.FromBase64String(data));
            }
            return null;
        }

        /// <summary>
        /// 判断是否日期
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsDateTime(string value)
        {
            DateTime time;
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }
            value = value.Trim();
            if (value.Length == 0)
            {
                return false;
            }

            // MS SQL 时间有效范围 [1753-01-01 12:00:00 ~ 9999-12-31 11:59:59]
            return (DateTime.TryParse(value, out time) && time.CompareTo(new DateTime(1753, 1, 1, 12, 0, 0)) >= 0 && time.CompareTo(new DateTime(9999, 12, 31, 11, 59, 59)) <= 0);
        }

        /// <summary>
        /// 判断是否Email
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static bool IsEMailAddress(string address)
        {
            if (address == null)
            {
                return false;
            }
            string pattern = @"\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$";
            Regex regex = new Regex(pattern);
            return regex.Match(address).Success;
        }

        /// <summary>
        /// 判断字符串是否可转化为Boolean类型. 值为 0, 1, true, false 时返回true
        /// </summary>
        /// <param name="str">值为0, 1, true, false时返回true</param>
        /// <returns></returns>
        public static bool IsBoolean(string str)
        {
            return str != null && (str == "0" || str == "1" || string.Compare(str, bool.FalseString, true) == 0 || string.Compare(str, bool.FalseString, true) == 0);
        }

        /// <summary>
        /// 判断字符串是否可转化为Boolean类型. 值为 0, 1, true, false, ok, cancel, yes, no 时返回true
        /// </summary>
        /// <param name="str">值为0, 1, true, false, ok, cancel, yes, no时返回true</param>
        /// <returns></returns>
        public static bool IsBooleanExt(string str)
        {
            bool b = IsBoolean(str);

            if (!b && str != null)
            {
                b = string.Compare(str, "OK", true) == 0 ||
                    string.Compare(str, "CANCEL", true) == 0 ||
                    string.Compare(str, "YES", true) == 0 ||
                    string.Compare(str, "NO", true) == 0;
            }

            return b;
        }

        /// <summary>
        /// 判断obj是否可转化为Guid类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsGuid(object obj)
        {
            return obj != null ? IsGuid(string.Format("{0}", obj)) : false;
        }

        /// <summary>
        /// 判断字符串是否可转化为Guid类型
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsGuid(string str)
        {
            return !string.IsNullOrEmpty(str) && new System.Text.RegularExpressions.Regex("^[A-F0-9]{8}(-[A-F0-9]{4}){3}-[A-F0-9]{12}$").IsMatch(str.ToUpper().Trim());
        }

        /// <summary>
        /// 判断是否手机号码（中国）
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static bool IsMobileNumber(string number)
        {
            if (number == null)
            {
                return false;
            }
            string pattern = @"^(\+?(\(\d{3}\))|(\d{3}\-))?1[3|4|5|8]\d{9}$";
            Regex regex = new Regex(pattern);
            return regex.Match(number).Success;
        }

        /// <summary>
        /// 判断是否数字格式
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static bool IsNumeric(char c)
        {
            //return char.IsDigit(c); // 此处未排除全角

            switch (c)
            {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    return true;
                default:
                    return false;
            }
        }

        /// <summary>
        /// 判断是否数字格式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNumeric(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }
            string str = value.Trim().TrimStart(new char[] { '+', '-' });
            if (str.Length == 0)
            {
                return false;
            }
            bool flag = false;
            for (int i = 0; i < str.Length; i++)
            {
                char c = str[i];
                if ((c != ',') || (i <= 0))
                {
                    if (c == '.')
                    {
                        if ((i == 0) || flag)
                        {
                            return false;
                        }
                        flag = true;
                    }
                    else if (!IsNumeric(c))
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 判断是否数字格式
        /// </summary>
        /// <param name="value"></param>
        /// <param name="NumberStyle"></param>
        /// <returns></returns>
        public static bool IsNumeric(string value, NumberStyles NumberStyle)
        {
            double num;
            if (string.IsNullOrEmpty(value))
            {
                return false;
            }
            value = value.Trim();
            if (value.Length == 0)
            {
                return false;
            }
            return double.TryParse(value, NumberStyle, CultureInfo.CurrentCulture, out num);
        }

        /// <summary>
        /// 判断是否URL
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsURL(string url)
        {
            if (url == null)
            {
                return false;
            }
            string pattern = @"\b(\S+)://(\S+)(?::(\S+))?\b";
            Regex regex = new Regex(pattern);
            return regex.Match(url).Success;
        }

        /// <summary>
        /// 测试s是否能转换为t所指定的类型
        /// </summary>
        /// <param name="s"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static bool IsMatch(string s, DataType t)
        {
            switch (t)
            {
                case DataType.Bool:
                    return IsBooleanExt(s);

                case DataType.DateTime:
                    return IsDateTime(s);

                case DataType.Decimal:
                    return IsNumeric(s);

                case DataType.Enum:
                    return true;

                case DataType.Guid:
                    return IsGuid(s);

                case DataType.Int:
                    return IsNumeric(s, NumberStyles.Integer);

                case DataType.String:
                default:
                    return true;
            }
        }

        /// <summary>
        /// 测试s能否匹配r(s包含r，包含r，s或r有一个为空时，返回false)。区分大小写
        /// </summary>
        /// <param name="s"></param>
        /// <param name="r"></param>
        /// <returns></returns>
        public static bool IsMatch(string s, string r)
        {
            return IsMatch(s, r, false);
        }

        /// <summary>
        /// 测试s能否匹配r(s包含r，s或r有一个为空时，返回false)。区分大小写
        /// </summary>
        /// <param name="s"></param>
        /// <param name="r"></param>
        /// <param name="ignoreCase">是否忽略大小写。true, 忽略大小写</param>
        /// <returns></returns>
        public static bool IsMatch(string s, string r, bool ignoreCase)
        {
            MatchMode mode = MatchMode.Exact;

            __getRegex(ref r, ref mode);

            return IsMatch(s, r, mode, ignoreCase);
        }

        /// <summary>
        /// 测试s能否匹配r(s包含r，s或r有一个为空时，返回false)。区分大小写
        /// </summary>
        /// <param name="s"></param>
        /// <param name="r"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static bool IsMatch(string s, string r, MatchMode mode)
        {
            return IsMatch(s, r, mode, false);
        }

        /// <summary>
        /// 测试s能否匹配r(s包含r，s或r有一个为空时，返回false)
        /// </summary>
        /// <param name="s"></param>
        /// <param name="r"></param>
        /// <param name="mode"></param>
        /// <param name="ignoreCase">是否忽略大小写。true, 忽略大小写</param>
        /// <returns></returns>
        public static bool IsMatch(string s, string r, MatchMode mode, bool ignoreCase)
        {
            if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(r))
                return false;

            switch (mode)
            {
                case MatchMode.Exact:
                    return string.Compare(s, r, ignoreCase) == 0;
                case MatchMode.Anywhere:
                    return System.Text.RegularExpressions.Regex.IsMatch(s, @"(" + r + ")+", ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                case MatchMode.Start:
                    return System.Text.RegularExpressions.Regex.IsMatch(s, @"^(" + r + ")+", ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                case MatchMode.End:
                    return System.Text.RegularExpressions.Regex.IsMatch(s, @"(" + r + ")+$", ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                case MatchMode.StartOrEnd:
                    return System.Text.RegularExpressions.Regex.IsMatch(s, @"(^(" + r + ")+)|((" + r + ")+$)", ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                default:
                    return System.Text.RegularExpressions.Regex.IsMatch(s, r, ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
            }
        }

        /// <summary>
        /// 获取第一个不为null且不为空字符串的文本
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string GetFirstNotNullAndNotEmptyText(params string[] s)
        {
            if (s == null) return null;

            foreach (string i in s)
                if (!string.IsNullOrEmpty(i)) return i;

            return null;
        }

        /// <summary>
        /// 连接字符串
        /// </summary>
        /// <param name="separator"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Join(string separator, IList value)
        {
            return Join(separator, value, ' ');
        }

        /// <summary>
        /// 连接字符串
        /// </summary>
        /// <param name="separator"></param>
        /// <param name="value"></param>
        /// <param name="valueMark"></param>
        /// <returns></returns>
        public static string Join(string separator, IList value, char valueMark)
        {
            if (string.IsNullOrEmpty(separator))
            {
                throw new ArgumentNullException("separator");
            }
            if ((value == null) || (value.Count == 0))
            {
                return string.Empty;
            }
            StringBuilder builder = new StringBuilder();
            foreach (object obj2 in value)
            {
                if (obj2 != null)
                {
                    string str = obj2.ToString();
                    if (str.Length != 0)
                    {
                        if (builder.Length != 0)
                        {
                            builder.Append(separator);
                        }

                        if (char.IsPunctuation(valueMark))
                        {
                            builder.Append(valueMark);
                            builder.Append(str);
                            builder.Append(valueMark);
                        }
                        else
                        {
                            builder.Append(str);
                        }
                    }
                }
            }
            return builder.ToString();
        }

        /// <summary>
        /// 在字符串左边补充长度
        /// </summary>
        /// <param name="s"></param>
        /// <param name="totalWidth"></param>
        /// <param name="paddingChar"></param>
        /// <returns></returns>
        public static string PadLeft(string s, int totalWidth, char paddingChar)
        {
            if (s == null)
            {
                s = string.Empty;
            }
            return s.PadLeft(totalWidth, paddingChar);
        }

        /// <summary>
        /// 在字符串右边补充长度
        /// </summary>
        /// <param name="s"></param>
        /// <param name="totalWidth"></param>
        /// <param name="paddingChar"></param>
        /// <returns></returns>
        public static string PadRight(string s, int totalWidth, char paddingChar)
        {
            if (s == null)
            {
                s = string.Empty;
            }
            return s.PadRight(totalWidth, paddingChar);
        }

        public static int SingleComputeLength(string s)
        {
            int byteCount = 0;
            if (s != null)
            {
                byteCount = Encoding.Default.GetByteCount(s);
            }
            return byteCount;
        }

        public static string SinglePadRight(string s, int totalWidth, char paddingChar)
        {
            if (s == null)
            {
                s = string.Empty;
            }
            int num = SingleComputeLength(s);
            int count = totalWidth - num;
            if (count <= 0)
            {
                return s;
            }
            string str = new string(paddingChar, count);
            return (s + str);
        }

        public static string SingleSubstring(string s, int startIndex, int length)
        {
            if (s == null)
            {
                return null;
            }
            byte[] bytes = Encoding.Default.GetBytes(s);
            int num = bytes.Length - startIndex;
            if (num < length)
            {
                length = num;
            }
            byte[] destinationArray = new byte[length];
            Array.Copy(bytes, startIndex, destinationArray, 0, length);
            return Encoding.Default.GetString(destinationArray);
        }

        /// <summary>
        /// 字符串转为字符编码
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static Encoding PerseEncoding(string s)
        {
            return PerseEncoding(s, Encoding.Default);
        }
        /// <summary>
        /// 字符串转为字符编码
        /// </summary>
        /// <param name="s"></param>
        /// <param name="defaultVlaue"></param>
        /// <returns></returns>
        public static Encoding PerseEncoding(string s, Encoding defaultVlaue)
        {
            Encoding encoding = defaultVlaue;
            if (!string.IsNullOrEmpty(s))
            {
                s = s.Trim();

                if (string.Compare(s, "ASCII", true) == 0)
                    encoding = Encoding.ASCII;
                else if (string.Compare(s, "BigEndianUnicode", true) == 0)
                    encoding = Encoding.BigEndianUnicode;
                else if (string.Compare(s, "Default", true) == 0)
                    encoding = Encoding.Default;
                else if (string.Compare(s, "Unicode", true) == 0)
                    encoding = Encoding.Unicode;
                else if (string.Compare(s, "UTF32", true) == 0)
                    encoding = Encoding.UTF32;
                else if (string.Compare(s, "UTF7", true) == 0)
                    encoding = Encoding.UTF7;
                else if (string.Compare(s, "UTF8", true) == 0)
                    encoding = Encoding.UTF8;
                else
                    try
                    {
                        encoding = Encoding.GetEncoding(s);
                    }
                    catch
                    {
                        encoding = defaultVlaue;
                    }
            }

            return encoding;
        }

        public delegate void KeyValueFilter<K, V>(ref K key, ref V value);
        /// <summary>
        /// 字符串转为字典
        /// </summary>
        /// <param name="s">将要分解的字符串</param>
        /// <param name="separ1">字典项的分隔字符</param>
        /// <param name="separ2">字典键与值的分隔字符</param>
        /// <returns></returns>
        public static Dictionary<string, string> ToDictionary(string s, char separ1, char separ2)
        {
            return __f4ad8b9e_toDictionary(s, separ1, separ2, null, null, null);
        }
        /// <summary>
        /// 字符串转为字典
        /// </summary>
        /// <param name="s">将要分解的字符串</param>
        /// <param name="separ1">字典项之间的分隔字符。如 &amp;</param>
        /// <param name="separ2">字典键与值之间的分隔字符。如 =</param>
        /// <param name="keyTrimChars">需要移除键前后的字符串。如 "</param>
        /// <param name="valueTrimChars">需要移除值前后的字符串。如 "</param>
        /// <returns></returns>
        public static Dictionary<string, string> ToDictionary(string s, char separ1, char separ2, char[] keyTrimChars, char[] valueTrimChars)
        {
            return __f4ad8b9e_toDictionary(s, separ1, separ2, keyTrimChars, valueTrimChars, null);
        }
        /// <summary>
        /// 字符串转为字典
        /// </summary>
        /// <param name="s">将要分解的字符串</param>
        /// <param name="separ1">字典项之间的分隔字符。如 &amp;</param>
        /// <param name="separ2">字典键与值之间的分隔字符。如 =</param>
        /// <param name="filter">处理键与值的匿名方法</param>
        /// <returns></returns>
        public static Dictionary<string, string> ToDictionary(string s, char separ1, char separ2, KeyValueFilter<string, string> filter)
        {
            return __f4ad8b9e_toDictionary(s, separ1, separ2, null, null, filter);
        }

        /// <summary>
        /// 字符串转为字典
        /// </summary>
        /// <param name="s">将要分解的字符串</param>
        /// <param name="separ1">字典项之间的分隔字符。如 &amp;</param>
        /// <param name="separ2">字典键与值之间的分隔字符。如 =</param>
        /// <param name="keyTrimChars">需要移除键前后的字符串。如 "</param>
        /// <param name="valueTrimChars">需要移除值前后的字符串。如 "</param>
        /// <param name="filter">处理键与值的匿名方法</param>
        /// <returns></returns>
        public static Dictionary<string, string> ToDictionary(string s, char separ1, char separ2, char[] keyTrimChars, char[] valueTrimChars, KeyValueFilter<string, string> filter)
        {
            return __f4ad8b9e_toDictionary(s, separ1, separ2, keyTrimChars, valueTrimChars, filter);
        }

        /// <summary>
        /// 字符串转为字典
        /// </summary>
        /// <param name="s">将要分解的字符串</param>
        /// <param name="separ1">字典项之间的分隔字符。如 &amp;</param>
        /// <param name="separ2">字典键与值之间的分隔字符。如 =</param>
        /// <param name="keyTrimChars">需要移除键前后的字符串。如 "</param>
        /// <param name="valueTrimChars">需要移除值前后的字符串。如 "</param>
        /// <param name="filter">处理键与值的匿名方法</param>
        /// <returns></returns>
        public static Dictionary<string, string> __f4ad8b9e_toDictionary(string s, char separ1, char separ2, char[] keyTrimChars, char[] valueTrimChars, KeyValueFilter<string, string> filter)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(s))
            {
                string[] itemArray = s.Split(separ1); // 分离项
                foreach (string item in itemArray)
                {
                    string[] keyValueArray = item.Split(separ2);// 分离键、值
                    if (keyValueArray.Length != 0)
                    {
                        string key = keyValueArray[0].Trim();
                        if (keyTrimChars != null)
                            key = key.Trim(keyTrimChars);

                        if (key.Length != 0)
                        {
                            string value = string.Empty;
                            if (keyValueArray.Length > 1)
                            {
                                value = item.Remove(0, item.IndexOf(separ2) + 1).Trim(); // 移除键名与分隔符

                                if (valueTrimChars != null && valueTrimChars.Length > 0)
                                    value = value.Trim(valueTrimChars);
                            }

                            if (filter != null)
                            {
                                filter(ref key, ref value);
                                if (string.IsNullOrEmpty(key))
                                    continue;
                            }

                            dictionary.Add(key, value);
                        }
                    }
                }
            }

            return dictionary;
        }

        /// <summary>
        /// 将obj转换为等效的字符串表示形式
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToBase64(object obj)
        {
            if (obj != null)
            {
                byte[] inArray = ByteHelper.Serialize(obj);
                if ((inArray != null) && (inArray.Length != 0))
                {
                    return Convert.ToBase64String(inArray);
                }
            }
            return null;
        }

        /// <summary>
        /// 字符串转为半角
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToDBC(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }
            char[] chArray = input.ToCharArray();
            for (int i = 0; i < chArray.Length; i++)
            {
                if (chArray[i] == '　')
                {
                    chArray[i] = ' ';
                }
                else if ((chArray[i] > 0xff00) && (chArray[i] < 0xff5f))
                {
                    chArray[i] = (char)(chArray[i] - 0xfee0);
                }
            }
            return new string(chArray);
        }

        /// <summary>
        /// 字符串转为全角
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToSBC(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }
            char[] chArray = input.ToCharArray();
            for (int i = 0; i < chArray.Length; i++)
            {
                if (chArray[i] == ' ')
                {
                    chArray[i] = '　';
                }
                else if (chArray[i] < '\x007f')
                {
                    chArray[i] = (char)(chArray[i] + 0xfee0);
                }
            }
            return new string(chArray);
        }

        /// <summary>
        /// 截短字符串，超出长度的字符以“...”代替
        /// </summary>
        /// <param name="s"></param>
        /// <param name="maxLen">截取的长度</param>
        /// <returns></returns>
        public static string Truncate(string s, int maxLen)
        {
            if (string.IsNullOrEmpty(s))
            {
                return s;
            }
            //if (maxLen == 0)
            //{
            //    return string.Empty;
            //}

            //s = s.Replace(System.Environment.NewLine, "  ").Replace("<br />", "  ").Replace("<br/>", "  ").Replace("<br>", "  ").Trim();

            //if (maxLen >= s.Length)
            //{
            //    return s;
            //}
            //else
            //{
            //    return s.Substring(0, Math.Max(0, maxLen - 3)) + "...";
            //}


            //s = System.Text.RegularExpressions.Regex.Replace(s, "<[^>]+>", "");
            //s = System.Text.RegularExpressions.Regex.Replace(s, "&[^;]+;", "");

            s = System.Text.RegularExpressions.Regex.Replace(s, "<[^>]+>|</[^>]+>", "");

            if (maxLen > 0 && s.Length > maxLen)
                return s.Substring(0, Math.Max(0, maxLen - 3)) + "...";

            return s;
        }

        /// <summary>
        /// 按字节长度截取字符串
        /// </summary>
        /// <param name="s">源字符串</param>
        /// <param name="byteLen">字节长度</param>
        /// <returns></returns>
        public static string SubByte(string s, int byteLen)
        {
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(s);
            int n = 0;  //  表示当前的字节数
            int i = 0;  //  要截取的字节数
            for (; i < bytes.GetLength(0) && n < byteLen; i++)
            {
                //  偶数位置，如0、2、4等，为UCS2编码中两个字节的第一个字节
                if (i % 2 == 0)
                {
                    n++;      //  在UCS2第一个字节时n加1
                }
                else
                {
                    //  当UCS2编码的第二个字节大于0时，该UCS2字符为汉字，一个汉字算两个字节
                    if (bytes[i] > 0)
                    {
                        n++;
                    }
                }
            }

            //  如果i为奇数时，处理成偶数
            if (i % 2 == 1)
            {
                if (bytes[i] > 0) //  该UCS2字符是汉字时，去掉这个截一半的汉字
                    i = i - 1;
                else // 该UCS2字符是字母或数字，则保留该字符
                    i = i + 1;
            }
            return System.Text.Encoding.Unicode.GetString(bytes, 0, i);
        }

        /// <summary>
        /// 判断字符串是否包含中文
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsCN(string s)
        {
            return Regex.IsMatch(s, @"[\u4E00 - \u9FA0]+");
        }


        /// <summary>
        /// 移除字符串两端的空白
        /// </summary>
        /// <param name="s">要搜索匹配项的字符串</param>
        /// <returns></returns>
        public static string Trim(string s)
        {
            return Trim(s, " ", MatchMode.StartOrEnd, false);
        }
        /// <summary>
        /// 移除字符串中的空白
        /// </summary>
        /// <param name="s">要搜索匹配项的字符串</param>
        /// <param name="mode">匹配模式</param>
        /// <returns></returns>
        public static string Trim(string s, MatchMode mode)
        {
            return Trim(s, " ", mode, false);
        }
        /// <summary>
        /// 移除字符串s1两端匹配的字符串s2（匹配开头与结尾）
        /// </summary>
        /// <param name="s1">要搜索匹配项的字符串</param>
        /// <param name="s2">要匹配的字符串。value、=value、*value、value*、*value*、%value%</param>
        /// <returns></returns>
        public static string Trim(string s1, string s2)
        {
            return Trim(s1, s2, false);
        }
        /// <summary>
        /// 移除字符串s1两端匹配的字符串s2（匹配开头与结尾）
        /// </summary>
        /// <param name="s1">要搜索匹配项的字符串</param>
        /// <param name="s2">要匹配的字符串。value、=value、*value、value*、*value*、%value%</param>
        /// <param name="ignoreCase">是否忽略大小写。true, 忽略大小写</param>
        /// <returns></returns>
        public static string Trim(string s1, string s2, bool ignoreCase)
        {
            if (__isRegexString(s2))
                return Replace(s1, s2, "", ignoreCase);
            else
                return Replace(s1, s2, "", MatchMode.StartOrEnd, ignoreCase);
        }
        /// <summary>
        /// 移除字符串s1中的子字符串s2
        /// </summary>
        /// <param name="s1">要搜索匹配项的字符串</param>
        /// <param name="s2">要匹配的字符串</param>
        /// <param name="mode">匹配模式</param>
        /// <returns></returns>
        public static string Trim(string s1, string s2, MatchMode mode)
        {
            return Trim(s1, s2, mode, false);
        }
        /// <summary>
        /// 移除字符串s1中的子字符串s2
        /// </summary>
        /// <param name="s1">要搜索匹配项的字符串</param>
        /// <param name="s2">要匹配的字符串</param>
        /// <param name="mode">匹配模式</param>
        /// <param name="ignoreCase">是否忽略大小写。true, 忽略大小写</param>
        /// <returns></returns>
        public static string Trim(string s1, string s2, MatchMode mode, bool ignoreCase)
        {
            return Replace(s1, s2, "", mode, ignoreCase);
        }


        /// <summary>
        /// 字符串替换。在s中查找s1，并用s2替换（区分大小写）
        /// </summary>
        /// <param name="s">要搜索匹配项的字符串</param>
        /// <param name="s1">要匹配的字符串。value、=value、*value、value*、*value*、%value%</param>
        /// <param name="s2">用于替换字符串</param>
        /// <returns></returns>
        public static string Replace(string s, string s1, string s2)
        {
            return Replace(s, s1, s2, false);
        }
        /// <summary>
        /// 字符串替换。在s中查找s1，并用s2替换
        /// </summary>
        /// <param name="s">要搜索匹配项的字符串</param>
        /// <param name="s1">要匹配的字符串。value、=value、*value、value*、*value*、%value%</param>
        /// <param name="s2">用于替换字符串</param>
        /// <param name="ignoreCase">是否忽略大小写。true, 忽略大小写</param>
        /// <returns></returns>
        public static string Replace(string s, string s1, string s2, bool ignoreCase)
        {
            MatchMode mode = MatchMode.Anywhere;

            __getRegex(ref s1, ref mode);

            return Replace(s, s1, s2, mode, ignoreCase);
        }
        /// <summary>
        /// 字符串替换。在s中查找s1，并用s2替换（区分大小写）
        /// </summary>
        /// <param name="s">要搜索匹配项的字符串</param>
        /// <param name="s1">要匹配的字符串</param>
        /// <param name="s2">用于替换字符串</param>
        /// <param name="mode">匹配模式</param>
        /// <returns></returns>
        public static string Replace(string s, string s1, string s2, MatchMode mode)
        {
            return Replace(s, s1, s2, mode, false);
        }
        /// <summary>
        /// 字符串替换。在s中查找s1，并用s2替换 (s1遇到特殊字符，请自行转义。如，“.”替换为“\\.”)
        /// </summary>
        /// <param name="s">要搜索匹配项的字符串</param>
        /// <param name="s1">要匹配的字符串</param>
        /// <param name="s2">用于替换字符串</param>
        /// <param name="mode">匹配模式</param>
        /// <param name="ignoreCase">是否忽略大小写。true, 忽略大小写</param>
        /// <returns></returns>
        public static string Replace(string s, string s1, string s2, MatchMode mode, bool ignoreCase)
        {
            if (s != null)
            {
                //if (s1 != null)
                //    s1 = s1.Replace(".", "\\.");

                switch (mode)
                {
                    case MatchMode.Anywhere:
                        s = System.Text.RegularExpressions.Regex.Replace(s, @"(" + s1 + ")", s2, ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                        break;
                    case MatchMode.Start:
                        s = System.Text.RegularExpressions.Regex.Replace(s, @"^(" + s1 + ")", s2, ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                        break;
                    case MatchMode.End:
                        s = System.Text.RegularExpressions.Regex.Replace(s, @"(" + s1 + ")$", s2, ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                        break;
                    case MatchMode.StartOrEnd:
                        s = System.Text.RegularExpressions.Regex.Replace(s, @"(^(" + s1 + "))|((" + s1 + ")$)", s2, ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                        break;
                    case MatchMode.Exact:
                        if (string.Compare(s, s1, ignoreCase) == 0)
                            s = s2;
                        break;
                    default:
                        s = System.Text.RegularExpressions.Regex.Replace(s, s1, s2, ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
                        break;
                }
            }

            return s;
        }

        /// <summary>
        /// 转换字符串为简体中文
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToSimplified(string s)
        {
            if (!string.IsNullOrEmpty(s))
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < s.Length; i++)
                {
                    string c = s.Substring(i, 1);
                    if (IsCN(c) && traditional.Contains(c))
                    {
                        sb.Append(simplified.Substring(i, 1));
                    }
                    else
                    {
                        sb.Append(c);
                    }
                }

                return sb.ToString();
            }
            else
            {
                return s;
            }
        }

        /// <summary>
        /// 转换字符串为繁体中文
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToTraditional(string s)
        {
            if (!string.IsNullOrEmpty(s))
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < s.Length; i++)
                {
                    string c = s.Substring(i, 1);
                    if (IsCN(c) && simplified.Contains(c))
                    {
                        sb.Append(traditional.Substring(i, 1));
                    }
                    else
                    {
                        sb.Append(c);
                    }
                }

                return sb.ToString();
            }
            else
            {
                return s;
            }
        }

        /// <summary>
        /// 将string转换为bool
        /// </summary>
        /// <param name="s">1,OK,YES,TRUE时，为true, 其他为false</param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static bool TryParse(string s, bool defaultValue)
        {
            if (IsBooleanExt(s))
            {
                return
                    string.Compare(s, "1", true) == 0 ||
                    string.Compare(s, "OK", true) == 0 ||
                    string.Compare(s, "YES", true) == 0 ||
                    string.Compare(s, "TRUE", true) == 0;
            }

            return defaultValue;
        }

        /// <summary>
        /// 将string转换为int
        /// </summary>
        /// <param name="s"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static int TryParse(string s, int defaultValue)
        {
            if (IsNumeric(s))
                return int.Parse(s);

            return defaultValue;
        }

        /// <summary>
        /// 将string转换为decimal
        /// </summary>
        /// <param name="s"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static decimal TryParse(string s, decimal defaultValue)
        {
            if (IsNumeric(s))
                return decimal.Parse(s);

            return defaultValue;
        }

        /// <summary>
        /// 将string转换为Guid
        /// </summary>
        /// <param name="s"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static Guid TryParse(string s, Guid defaultValue)
        {
            if (IsGuid(s))
                return new Guid(s);

            return defaultValue;
        }

        /// <summary>
        /// 将string转换为DateTime
        /// </summary>
        /// <param name="s"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static DateTime TryParse(string s, DateTime defaultValue)
        {
            if (IsDateTime(s))
                return DateTime.Parse(s);

            return defaultValue;
        }

        #region private

        /// <summary>
        /// 判断字符串是否为可匹配串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static bool __isRegexString(string str)
        {
            return str.StartsWith("=") ||
                str.StartsWith("*") ||
                str.StartsWith("%") ||
                str.EndsWith("*") ||
                str.EndsWith("%") ||
                str.EndsWith("?");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="regex"></param>
        /// <param name="mode"></param>
        private static void __getRegex(ref string regex, ref MatchMode mode)
        {
            if (!string.IsNullOrEmpty(regex))
            {
                int length = regex.Length;
                if (length > 2 && regex.StartsWith("%") && regex.EndsWith("%")) // 匹配任意
                {
                    regex = regex.Substring(1, length - 2);
                    mode = MatchMode.Anywhere;
                }
                else if (regex.StartsWith("=")) // 精确（等于）
                {
                    regex = regex.Substring(1);
                    mode = MatchMode.Exact;
                }
                else
                {
                    bool matchStart = regex.EndsWith("*") || regex.EndsWith("%");
                    bool matchEnd = regex.StartsWith("*") || regex.StartsWith("%");
                    if (length > 2 && matchStart && matchEnd) // 匹配开头或结尾
                    {
                        regex = regex.Substring(1, length - 2);
                        mode = MatchMode.StartOrEnd;
                    }
                    else if (matchStart) // 匹配开头
                    {
                        regex = regex.Substring(0, length - 1);
                        mode = MatchMode.Start;
                    }
                    else if (matchEnd) // 匹配结尾
                    {
                        regex = regex.Substring(1, length - 1);
                        mode = MatchMode.End;
                    }
                    else // 精确（等于）
                    {
                        //mode = MatchMode.Exact;
                    }
                }
            }
        }

        #endregion


        /// <summary>
        /// 匹配模式（主要用于操作字符串）
        /// </summary>
        public enum MatchMode
        {
            /// <summary>
            /// 匹配任意
            /// </summary>
            [Description("匹配任意")]
            Anywhere = 0,
            /// <summary>
            /// 匹配开头
            /// </summary>
            [Description("匹配开头")]
            Start = 1,
            /// <summary>
            /// 匹配结尾
            /// </summary>
            [Description("匹配结尾")]
            End = 2,
            /// <summary>
            /// 匹配开头或结尾
            /// </summary>
            [Description("匹配开头或结尾")]
            StartOrEnd = 4,
            /// <summary>
            /// 匹配整个字符串
            /// </summary>
            [Description("匹配整个字符串")]
            Exact = 8,
        }
    }
}